from datetime import timedelta
from markupsafe import Markup

from odoo import api, fields, tools, models, _
from odoo.exceptions import UserError, ValidationError


class ProductUov(models.Model):
    _name = 'product.uom.value'
    _description = 'Product UoM Values'

    product_id = fields.Many2one('product.template', "Product")
    uom_id = fields.Many2one('uom.uom', "UoM")
    required = fields.Boolean(string="Is Required")
    uom_value = fields.Float(string='Uom Value', digits=(16, 5))
    uom_name_id = fields.Many2one('uom.name', string='Uom Name')
    record_name = fields.Char(string='Project Record', related='uom_id.record_name')

    @api.onchange('uom_id')
    def _onchange_uom_type(self):
        self.uom_value = 0
        if self.uom_id:
            self.uom_name_id = self.uom_id.uom_name_id.id

    def _cron_update_uom_name_id(self):
        square_mset = self.env.ref("pcbmanufact.uom_name_square_mset").id
        square_mpcs = self.env.ref("pcbmanufact.uom_name_square_mpcs").id
        square_pnl = self.env.ref("pcbmanufact.uom_name_square_pnl").id
        mm = self.env.ref("pcbmanufact.uom_name_mm").id
        pnl_sheet = self.env.ref("pcbmanufact.uom_name_pnl_sheet").id
        pcs_sheet = self.env.ref("pcbmanufact.uom_name_pcs_sheet").id
        pcs_pnl = self.env.ref("pcbmanufact.uom_name_pcs_pnl").id
        pcs_set = self.env.ref("pcbmanufact.uom_name_pcs_set").id
        objs = self.search([])
        # objs = self.browse()
        for i, obj in enumerate(objs):
            if obj.uom_id.name == 'SETA':
                obj.uom_name_id = square_mset
            elif obj.uom_id.name == 'PCSA':
                obj.uom_name_id = square_mpcs
            elif obj.uom_id.name == 'PNLA':
                obj.uom_name_id = square_pnl
            elif obj.uom_id.name in ['SHETL', 'SHETW', 'PNLL', 'PNLW', 'SetL', 'SetW',
                                     'PCSL', 'PCSW', 'SETL', 'SETW', 'PCS Width', 'PCS Length',
                                     'Panel Width', 'Panel Length', 'Set Width', 'Set Length']:
                obj.uom_name_id = mm
            elif obj.uom_id.name == 'SHEET':
                obj.uom_name_id = pnl_sheet
            elif obj.uom_id.name == 'PCSPS':
                obj.uom_name_id = pcs_sheet
            elif obj.uom_id.name == 'PANEL':
                obj.uom_name_id = pcs_pnl
            elif obj.uom_id.name == 'SET':
                obj.uom_name_id = pcs_set
            else:
                pass
        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'type': 'success',
                'title': _("Update Success"),
                'message': "更新完成！",
                'next': {
                    'type': 'ir.actions.act_window_close'
                },
            }
        }

    def write(self, vals):
        self._update_uom_value(vals)
        return super().write(vals)

    def _update_uom_value(self, values):
        product_ids = self.mapped('product_id')
        if 'uom_value' not in values:
            return
        new_uom_value = values.get('uom_value', '')
        for product in product_ids:
            lines = self.filtered(lambda x: x.product_id == product)
            message = ''
            for line in lines:
                message += Markup(f"<li>{line.uom_id.name}:  {line.uom_value} -> {new_uom_value} <br/>")

            if not message:
                continue
            msg = Markup(f"<b>单位明细已更新</b><ul>{message}</ul>")
            product.message_post(body=msg)


class ShowUomName(models.Model):
    _name = 'uom.name'

    name = fields.Char(string='Uom Name')
